<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use addons\V2\admin\model\Order;
use think\facade\Cache;
use think\facade\Event;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,is_active,level_id,team_id,team_total,my_total,small_total');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,team_total,my_total,level_id,team_id,small_total,now_total,newly_total');
    }

    /**
     * 原点 2020年8月22日16:25:27 记录推荐关系
     *
     * @param $uid -- 新会员ID
     * @param $code -- 新会员编号
     * @param int $status -- 状态：默认0普通会员1正式会员
     * @param $parent_id -- 推荐人的ID
     * @return array
     */
    public function record($uid, $code, $parent_id)
    {
        try {
            $algebra = 1;
            $time = time();
            if ($parent_id) {
                $p_id = $parent_id;
                $insert = [];
                while ($parent = User::where('id', $p_id)->field('id,code,parent_id,is_active')->find()) {
                    if ($parent) {
                        if($parent->is_active==2)
                        {
                            $status = 1;
                        }else{
                            $status = 0;
                        }
                        $data['uid'] = $parent->id;
                        $data['code'] = $parent->code;
                        $data['status'] = $status;
                        $data['new_uid'] = $uid;
                        $data['new_code'] = $code;
                        $data['algebra'] = $algebra;
                        $data['create_time'] = $time;
                        $insert[] = $data;
                        $p_id = $parent->parent_id;
                    }
                    $algebra++;
                }
                $this->insertAll($insert);
            }
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
            User::whereIn('id', $all_id)->inc('now_total', floatval($amount))->update();
        }

    }

    public static function jd_award($amount,$u_id)
    {
        try {
            $list = parent::where('new_uid', $u_id)->field('id,uid,algebra')->order('algebra', 'asc')->select();//团队列表
            $jd_award = Cache::get('system')['jd_award'];//见点奖
            foreach ($list as $k=>$v)
            {
                $num = User::where(['parent_id'=>$v->uid,'is_active'=>2])->count();

                if($num)
                {
                    if($num>10)
                    {
                        $num = 10;
                    }
                    $generation_num = 'generation_'.$num;
                    $generation = Cache::get('system')[$generation_num];//见点奖代数
                    if($generation>=$v->algebra)
                    {
                        $amounts = bcmul((string)$amount, (string)$jd_award, 2);
                        Relation::awardPrizes($v->uid,$amounts,'见点奖', '+',$u_id, 2);
                    }
                }
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }



    public static function awardPrizes($u_id,$amount,$msg,$fx,$source,$category)
    {
        try {
            if($amount>0)
            {
                $order = Order::where(['uid'=>$u_id,'pay_state'=>2,'is_release'=>2])->find();
                if($order)
                {
                    $releases = $order->release + $amount;
                    if($releases > $order->give)
                    {
                        $order->is_release = 1;
                        $order->release_time = time();
                        $amount = $order->give - $order->release;
                    }
                    $order->release = $order->release+$amount;
                    $order->save();
                    $reward_ratio = Cache::get('system')['reward_ratio'];
                    $integral = bcmul((string)$amount, (string)$reward_ratio, 2);
                    $bonus = $amount - $integral;
                    Target::Account()->basics($u_id, 'integral', $amount,$integral, $msg, $fx)
                        ->createNormal($source);
                    Target::Account()->basics($u_id, 'bonus', $amount,$bonus, $msg, $fx)
                        ->createBonus($source, $category);
                    //            Target::Account()->basics($u_id, 'integral', $amount, '加速释放', '-')
                    //                ->createNormal($u_id);
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $amount]);
                }
            }
        } catch (\Exception $e) {
            dump($e->getMessage());die;
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    //小区业绩
    public static function small_total($u_id): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $u_id)->field('id,uid,algebra')->order('algebra', 'asc')->select();//团队列表
            foreach ($list as $r=>$item) {
                $num =  User::where(['parent_id'=>$item->uid,'is_active'=>2])->count();
                if($num>1)
                {
                    $zt_user = User::where(['parent_id'=>$item->uid,'is_active'=>2])->order('team_total','desc')->field('id,my_total,team_total')->find();//直推人员最大的
                    $min = $item->user->team_total-$zt_user->team_total-$zt_user->my_total;//小区
                    User::update(['small_total'=>$min], ['id' => $item->uid]);//修改小区业绩
                }

            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    //分享奖
    public static function recommend($p_uid,$amount,$uid)
    {
        try {
            $number = User::where(['parent_id'=>$p_uid,'is_active'=>2])->count();
            if($number<=3)
            {
                $share = Cache::get('system')['share_1'];
            }else{
                $share = Cache::get('system')['share_2'];
            }
            $amounts = bcmul((string)$amount, (string)$share, 2);
            Relation::awardPrizes($p_uid,$amounts,'分享奖', '+',$uid, 1);
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }



    //推荐收益
    public static function promotion($p_uid,$uid,$amount)
    {
        try {
            $integral_tp = Cache::get('system')['integral_tp'];

            $amounts = bcmul((string)$amount, (string)$integral_tp, 2);

            Target::Account()->basics($p_uid, 'commission', $amounts, '推荐收益', '+')
                ->createBonus($uid, 1);

            Event::trigger('Statistics', ['key' => 'expend', 'value' => $amounts]);
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }


    //代理奖
    public static function agent($agent_uid,$uid,$amount)
    {
        try {
            $agent = Cache::get('system')['agent'];

            $amounts = bcmul((string)$amount, (string)$agent, 2);

            Target::Account()->basics($agent_uid, 'commission', $amounts, '代理收益', '+')
                ->createBonus($uid, 7);

            User::where('id', $agent_uid)->inc('agency_income', floatval($amounts))->update();//代理收益累计

            Event::trigger('Statistics', ['key' => 'expend', 'value' => $amounts]);
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }




    //分红
    public static function bonus(): array
    {
        try {
            $real_amount = User::where('newly_total','>',0)->sum('newly_total');//系统新增业绩
            $my_total = User::where('my_total','>',0)->sum('my_total');//全部个人业绩
            $joint_bonus_tp = Cache::get('system')['joint_bonus_tp'];
            $amounts = bcmul((string)$real_amount,(string)$joint_bonus_tp,2);//奖励
            $users =  User::where('my_total','>',0)->field('id,my_total,divvy_num')->select();

            $num = 0;
            foreach ($users as $key=>$value)
            {
                $amount = round($value->my_total/$my_total*$amounts,2);
                if($amount>0)
                {
                    $capping = Cache::get('system')['capping'];//封顶倍数
                    $capping = bcmul((string)$value->my_total,(string)$capping,2);//封顶数量
                    if($amount+$value->divvy_num>$capping)
                    {
                        $amount = $capping - $value->divvy_num;
                    }
                    if($amount>0)
                    {
                        Target::Account()
                            ->basics($value->id, 'divvy', $amount, '分红奖励', '+')
                            ->createBonus($value->id, 4);
                        User::where('id', $value->id)->inc('divvy_num', floatval($amount))->update();//新增分红
                    }

                }
                User::where('id',$value->id)->update(['newly_total'=>0]);
                $num+=$amount;
            }


            Event::trigger('Statistics', ['key' => 'expend', 'value' => $num]);

            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            dump($e->getMessage());die;
        }
    }


    /**
     * @param $uid
     * @param $total
     * @return array|int[]
     * 原点 2023年7月12日14:16:53 团队奖
     */
    public static function teamBonus($uid, $amount): array
    {
        try {

            $list = parent::with('user')->where(['new_uid'=>$uid])
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            $team_total = 0;
            $level_id = 0;
            $flat_id = 0;
            $totals = 0;
            foreach ($list as $item) {
                $level = TeamLevel::find($item->user->team_id);
                if($level_id<$item->user->team_id)
                {
                    $team_amount = $level->reward - $team_total;
                    $total = bcmul((string)$amount, (string)$team_amount, 2);
                    Relation::awardPrizes($item->user->id,$total,'团队奖', '+',$uid, 3);


                    $users = User::where('team_id','>',$item->user->team_id)->where('parent_id',$item->user->id)->field('id,team_id')->select();

                    foreach ($users as $k=>$v)
                    {
                        $p_level = TeamLevel::find($v->team_id);
                        $transcend = bcmul((string)$total, (string)$p_level->transcend, 2);
                        Relation::awardPrizes($v->id,$transcend,'超越奖', '+',$uid, 5);
                    }

                    $level_id = $item->user->team_id;
                    $team_total = $level->reward;
                    $totals = $total;
                }elseif($level_id==$item->user->team_id&&$flat_id!=$level_id)
                {

                    $equal = bcmul((string)$totals, (string)$level->equal, 2);
                    if($equal>0)
                    {
                        Relation::awardPrizes($item->user->id,$equal,'平级奖', '+',$uid, 4);
                    }

                    $flat_id = $item->user->team_id;
                }


            }

            return ['code' => 1];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //业绩分红
    public static function Performance_dividends(): array
    {
        try {
            $newly_total = User::where('newly_total','>',0)->where(['delete_time'=>0])->sum('newly_total');

            $performance = Cache::get('system')['performance'];

            $total = bcmul((string)$newly_total, (string)$performance, 2);

            $expendTotal = 0;
            if($total>0)
            {
                $user = User::where('my_count','>',0)->where(['delete_time'=>0])->field('id,my_count,my_total,performance')->select();
                $my_counts = User::where('my_count','>',0)->where(['delete_time'=>0])->sum('my_count');
                $number = bcdiv((string)$total, (string)$my_counts, 2);
                foreach ($user as $k=>$v)
                {
                    $amount = bcmul((string)$number, (string)$v->my_count, 2);
                    $performance_capping = Cache::get('system')['performance_capping'];//倍数
                    $num = $v->my_total*$performance_capping;
                    if($v->performance+$amount > $num)
                    {
                        $amount = $num - $v->performance;
                    }
                    if($amount>0)
                    {
                        Target::Account()->basics($v->id, 'commission', $amount, '业绩分红', '+')
                            ->createBonus($v->id, 8);
                        User::where('id', $v->id)->inc('performance', floatval($amount))->update();//业绩分红累计
                    $expendTotal +=$amount;
                    }
                }
            }
            if ($expendTotal > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    /**
     * @param $uid
     * @param $total
     * @return array|int[]
     * 原点 2023年7月12日14:16:53 促销收益
     */
    public static function teamPromotion($uid, $amount): array
    {
        try {

            $list = parent::with('user')->where(['new_uid'=>$uid,'status'=>1])
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            $team_total = 0;
            $level_id = 0;
            $expendTotal = 0;
            $flat_id = 0;
            $equal = array();
            foreach ($list as $item) {
                if($level_id<$item->user->team_id)
                {
                    $level = TeamLevel::find($item->user->team_id);
                    if(!$item->user->is_hesitate)
                    {
                        if ($level->reward)
                        {
                            $team_amount = $level->reward - $team_total;
                            $total = bcmul((string)$amount, (string)$team_amount, 2);
                            if($total>0)
                            {
                                Target::Account()->basics($item->user->id, 'commission', $total, '促销收益', '+')
                                    ->createBonus($uid, 2);

                                $expendTotal+=$total;
                            }
                        }
                    }

                    $level_id = $item->user->team_id;
                    $team_total = $level->reward;
                }elseif ($level_id==$item->user->team_id)
                {
                    $equal[$level_id][] = $item->user->id;
//                    $flat_id = $item->user->team_id;
                }

            }
            foreach ($equal as $key=>$value)
            {
               $num = count($value);
                $level = TeamLevel::find($key);
                if($level->equal)
                {
                    $equal_amount = bcmul((string)$amount, (string)$level->equal, 2);
                    $flat_total = bcdiv((string)$equal_amount, (string)$num, 2);
                    if($flat_total>0)
                    {
                        foreach ($value as $ke=>$va)
                        {
                            Target::Account()->basics($va, 'commission', $flat_total, '平级奖励', '+')
                                ->createBonus($uid, 3);
                            $expendTotal+=$flat_total;
                        }
                    }
                }
            }

            if ($expendTotal > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //合伙人分红
    public static function partner(): array
    {
        try {
            $users = User::where(['is_partner'=>1,'delete_time'=>0])->field('id,my_count')->select();
            $partner_num = User::where('partner','>',0)->where(['delete_time'=>0])->sum('partner');
            $my_counts = User::where('my_count','>',0)->where(['is_founder'=>1,'delete_time'=>0])->sum('my_count');
            if($my_counts>0)
            {
                $expendTotal = 0;
                $partner = Cache::get('system')['partner'];
                $flat_total = bcmul((string)$partner_num, (string)$partner, 2);
                $number = bcdiv((string)$flat_total, (string)$my_counts, 2);
                foreach ($users as $k=>$v)
                {
                    $bonus = bcmul((string)$number, (string)$v->my_count, 2);
                    if($bonus>0) {
                        Target::Account()->basics($v->id, 'commission', $bonus, '合伙人分红', '+')
                            ->createBonus($v->id, 5);
                        $expendTotal += $bonus;
                    }
                }

                if ($expendTotal > 0) {
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
                }
            }

            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //创始人分红
    public static function founder(): array
    {
        try {
            $users = User::where(['is_founder'=>1,'delete_time'=>0])->field('id,my_count')->select();
            $founder_num = User::where('founder','>',0)->where(['delete_time'=>0])->sum('founder');
            $my_counts = User::where('my_count','>',0)->where(['is_founder'=>1,'delete_time'=>0])->sum('my_count');
            if($my_counts>0)
            {
                $expendTotal = 0;
                $founder = Cache::get('system')['founder'];
                $flat_total = bcmul((string)$founder_num, (string)$founder, 2);
                $number = bcdiv((string)$flat_total, (string)$my_counts, 2);
                foreach ($users as $k=>$v)
                {
                    $bonus = bcmul((string)$number, (string)$v->my_count, 2);
                    if($bonus>0) {
                        Target::Account()->basics($v->id, 'commission', $bonus, '创始人分红', '+')
                            ->createBonus($v->id, 6);
                        $expendTotal += $bonus;
                    }
                }

                if ($expendTotal > 0) {
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
                }
            }

            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }




    //股东分红
    public static function shareholder(): array
    {
        try {
            $users = User::where(['is_shareholder'=>1,'delete_time'=>0])->column('id');
            $shareholder_num = User::where('shareholder','>',0)->sum('shareholder');
            $num = count($users);
            if($num>0)
            {
                $expendTotal = 0;
                $shareholder = Cache::get('system')['shareholder'];
                $flat_total = bcmul((string)$shareholder_num, (string)$shareholder, 2);
                $bonus = bcdiv((string)$flat_total, (string)$num, 2);
                foreach ($users as $k=>$v)
                {
                    if($bonus>0) {
                        Target::Account()->basics($v, 'commission', $bonus, '股东分红', '+')
                            ->createBonus($v, 4);
                        $expendTotal += $bonus;
                    }
                }

                if ($expendTotal > 0) {
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
                }
            }

            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 团队升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::where('new_uid', $uid)->with('user')->field('id,uid')->select();//用户上级
            foreach ($list as $item) {
                $next_level = TeamLevel::where('id','>',$item->user->team_id)->order('id','asc')->find();
                if($next_level)
                {
                   $number = User::where('parent_id',$item->uid)->where('team_id','>=',$item->user->team_id)->count();

                    if($number>=$next_level->zt_count&&$item->user->small_total>=$next_level->small_total)
                    {
                        User::update(['team_id' => $next_level->id], ['id' => $item->uid]);
                    }
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
